import { getHeader } from 'h3';
import { AdminModel } from '~/server/models/admin.model';
import { verifyToken } from '~/server/utils/util.crypto';

// 获取当前管理员用户信息
export default defineEventHandler(async (event): Promise<any> => {
	try {
		// 获取 token
		const token = getCookie(event, 'token');

		if (!token) return { code: 0, message: '未登录' };

		const payload = await verifyToken(token.split(' ')[1]);

		if (!payload?.id) return { code: 0, message: '无效token' };

		const user = await AdminModel.findById(payload.id).lean();

		if (!user) return { code: 0, message: '用户不存在' };

		// 只返回部分信息
		return {
			code: 1,
			data: {
				_id: user._id,
				username: user.username,
				nickname: user.nickname,
				avatar: user.avatar,
			},
		};
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
